/*
 * ApplicationController.java
 *
 * Created on 02 March 2006, 15:23
 */

package web;

import java.io.*;
import java.util.Date;

import javax.servlet.*;
import javax.servlet.http.*;
import web.services.Service;
import web.services.ServiceFactory;
import web.util.BusinessFacadeDelegate;
import web.util.BusinessFacadeDelegateFactory;


/**
 *
 * @author Phil
 * @version
 */
public class ApplicationController extends HttpServlet {
    
    private static final String DEFAULT_PATH = "home";
    private static final String DEFAULT_SERVICE_CLASS = "Home";
    private static final String SERVICE = "Service";
    public static final String SERVICE_NEXT = "SubmitService";
    public static final String BUSINESS_DELEGATE_REF = "BusinessFacadeDelegate";
    public static final String SERVICE_FRAGMENT_REF = "ServiceFragment";
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        String servicePath = DEFAULT_PATH;
        String serviceClass = DEFAULT_SERVICE_CLASS + SERVICE;
        String fragmentPath = "";
        BusinessFacadeDelegate delegate;
        
        //ServletContext context = getServletContext();
        
        HttpSession session = request.getSession();
        String pathInfo = request.getPathInfo();
        
        if (null != pathInfo && !(session.isNew()) && pathInfo.length() > 1) {
            pathInfo = pathInfo.substring(1);
            
            String[] splitPath = pathInfo.split("/");
            splitPath = capitaliseStringArray(splitPath);
            if(splitPath.length <= 1) {
                serviceClass = splitPath[0] + SERVICE;
            } 
            else {
                serviceClass = splitPath[0] + splitPath[1] + SERVICE;            
                fragmentPath = splitPath[1];
            }
            
            servicePath = splitPath[0];
        }
        
        try {
            delegate = (BusinessFacadeDelegate) session.getAttribute(BUSINESS_DELEGATE_REF);
            
            if (null == delegate) {
                delegate = BusinessFacadeDelegateFactory.getDelegate(null); // no user - not logged in yet!
                session.setAttribute(BUSINESS_DELEGATE_REF, delegate);
            }
            
            dispatchService(request, response, serviceClass, fragmentPath, servicePath);
            
            /*activeService = ServiceFactory.getInstance().getService(serviceClass);
            
            session.setAttribute(SERVICE_NEXT,activeService.executePreDispatch(request, context));
            RequestDispatcher forwarder = request.getRequestDispatcher("/" + servicePath);
            session.setAttribute("date", new Date());
            session.setAttribute(SERVICE_FRAGMENT_REF, fragmentPath);
            session.setAttribute(SERVICE, servicePath);
            forwarder.forward(request, response);
            activeService.executePostDispatch(request, context);*/
        } catch (Exception e) {
            session.setAttribute(Service.ATTRIBUTE_EXCEPTION, e);
            
            servicePath = (String)session.getAttribute(Service.ATTRIBUTE_LAST_SERVICE);
            fragmentPath = (String)session.getAttribute(Service.ATTRIBUTE_LAST_FRAGMENT);
            serviceClass = servicePath + fragmentPath + SERVICE;
            
            try {
                dispatchService(request, response, serviceClass, fragmentPath, servicePath);
                session.setAttribute(Service.ATTRIBUTE_EXCEPTION, null);
            } catch (Exception e2) {
                throw new ServletException("A serious error was encountered while serving this request. Please give up!\n\n" + e2.getMessage() + e.getMessage());
            }
        }
    }
    
    private String[] capitaliseStringArray(String[] strings) {
        for (int i=0; i < strings.length; i++) {
            strings[i] = Character.toUpperCase(strings[i].charAt(0)) + strings[i].substring(1);
        }       
        return strings;
    }
    
    private void dispatchService(HttpServletRequest request, 
                                HttpServletResponse response,
                                String serviceClass, 
                                String fragmentPath, 
                                String servicePath)
                                    throws Exception {
            Service activeService = ServiceFactory.getInstance().getService(serviceClass);
            ServletContext context = getServletContext();
            HttpSession session = request.getSession();
            
            session.setAttribute(SERVICE_NEXT,activeService.executePreDispatch(request, context));
            RequestDispatcher forwarder = request.getRequestDispatcher("/" + servicePath);
            session.setAttribute("date", new Date());
            session.setAttribute(SERVICE_FRAGMENT_REF, fragmentPath);
            session.setAttribute(SERVICE, servicePath);
            forwarder.forward(request, response);
            activeService.executePostDispatch(request, context);
            session.setAttribute(Service.ATTRIBUTE_LAST_SERVICE, servicePath);
            session.setAttribute(Service.ATTRIBUTE_LAST_FRAGMENT, fragmentPath);
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
